import { createSSRApp } from 'vue';
import * as Pinia from 'pinia';
import App from './App.vue';
import request from '@/request';
import { useAppid } from '@/hooks';
import '@/utils/polyfill';

export function createApp() {
  const app = createSSRApp(App);
  app.use(Pinia.createPinia());
  const appid = useAppid();

  app.config.globalProperties.appid = appid;
  app.config.globalProperties.$http = request;
  app.config.globalProperties.imgBaseUrl = import.meta.env.VITE_IMG_BASE_URL;

  app.config.globalProperties.goBack = () => {
    const pages = getCurrentPages();

    if (pages.length === 1 && pages[0].route?.replace(/^\//, '') !== 'pages/index/index') {
      return uni.redirectTo({ url: '/pages/index/index' });
    }

    uni.navigateBack();
  };

  app.config.globalProperties.navigateTo = uni.navigateTo;

  app.mixin({
    // 主动定义onShareAppMessage，通知小程序显示分享菜单
    onShareAppMessage(e) {
      const pages = getCurrentPages();

      let fullPath = pages.at(-1)?.$vm?.$scope?.$page?.fullPath ?? '/pages/index/index';

      console.log('分享路径：', fullPath);

      return {
        title: '漫画',
        path: `${fullPath}${fullPath.indexOf('?') > -1 ? '&' : '?'}${1}`,
        templateId: 'ansk24c0detf09ch80', //模板ID
        desc: '来一起看漫画吧',
      };
    },
  });

  console.log(app.config.globalProperties.appName);

  return {
    app,
    Pinia,
  };
}
